# coding=utf-8
import traceback
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.views import logout as django_logout
from django.contrib.auth import login as django_login

from db.models import User
from db.forms import UserForm
from store_manage.utils import session
from store_manage.utils import create_success_dict
from store_manage.utils import create_failure_dict
from store_manage.utils import paginator


def all(request, *args, **kwargs):
    fields = ['id', 'username', 'first_name', 'email', 'is_superuser',
              'is_activate', 'is_staff', 'date_joined']
    q = User.objects.all().values(fields)
    
    return paginator(request, q)

def add(request, *args, **kwargs):
    pass


def delete(request, *args, **kwargs):
    pass


def edit(request, *args, **kwargs):
    pass


def get(request, *args, **kwargs):
    pass


def login(request, *args, **kwargs):
    username = request.POST.get('username', None)
    password = request.POST.get('password', None)
    if not (username and password):
        return create_failure_dict(msg='用户名或密码错误')

    try:
        user = authenticate(username=username, password=password)
        if user:
            session.save_user(request, user)
            django_login(request, user)
            return create_success_dict()
        return create_failure_dict(msg='用户名或密码错误')
    except:
        return create_failure_dict(msg='用户名或密码错误')

        
def logout(request, *args, **kwargs):
    session.clear_user(request)
    return django_logout(request, '/')


def importer(request, *args, **kwargs):
    pass


def export(request, *args, **kwargs):
    pass


